package com.example.com.skills_utf8;



import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import com.utils.Utils1;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

/**
 * An example of how to use the NFC foreground dispatch APIs. This will intercept any MIME data
 * based NDEF dispatch as well as all dispatched for NfcF tags.
 */
public class ForegroundDispatch_nfc1 extends Activity {
	
	
	private ForegroundDispatch_nfc1 activity = this;
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private EditText mText;
    private int mCount = 0;

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);

        setContentView(R.layout.background_dispatch);
        mText = (EditText) findViewById(R.id.et);

        mAdapter = NfcAdapter.getDefaultAdapter(this);

        // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
        // will fill in the intent with the details of the discovered tag before delivering to
        // this activity.
        mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        // Setup an intent filter for all MIME based dispatches
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        try {
            ndef.addDataType("*/*");
   //         tag.addDataType("*/*");
        } catch (MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mFilters = new IntentFilter[] {
                ndef,
                tech,
                tag
        };

        // Setup a tech list for all NfcF tags
        mTechLists = new String[][] { new String[] { NfcF.class.getName() } };
     
        
        
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdapter != null) mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
                mTechLists);
    }

    
    /*
    Obtaining information from intents

If an activity starts because of an NFC intent, you can obtain information about the scanned NFC tag from the intent. Intents can contain the following extras depending on the tag that was scanned: 
•EXTRA_TAG (required): A Tag object representing the scanned tag.
•EXTRA_NDEF_MESSAGES (optional): An array of NDEF messages parsed from the tag. This extra is mandatory on intents.
•{@link android.nfc.NfcAdapter#EXTRA_ID (optional): The low-level ID of the tag.
    */
    @Override
    public void onNewIntent(Intent intent) {
        Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
        mText.setText("Discovered tag " + ++mCount + " with intent: " + intent);
        
        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) //ndef
        {
   
        	Tag detectedTag = intent
					.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        	
        	if(detectedTag != null){
        		System.out.println("tag");
        		writeNdefTag( intent );
        	}
        	
        	
        }
        else if(intent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED)) { //tech
        	
        }
        else{   // tag     MifareClassic射频卡
         	
        	writeNdefTag( intent );
            
        	
        }
     
        
    }
    
    

    private void writeNdefTag(Intent in){
    	boolean bCompleted = false;
    	
        Tag tag = in.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Ndef ndef = Ndef.get(tag);
        try {

 //这一句别丢了，读nfc标签的时候不需要这句，因为那时数据直接就在intent中。
            ndef.connect(); 

 //构造一个合适的NdefMessage。你可以看到代码里用了NdefRecord数组，只不过这个数组里只有一个record
            NdefMessage ndefMsg = new NdefMessage(new NdefRecord[]{createRecord()});
            ndef.writeNdefMessage(ndefMsg);
            bCompleted = true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        if(bCompleted){
        	System.out.println("成功写入.");
        	Utils1.showToastShort(activity, "成功写入~");
        	
        }
        
     }
    
     private NdefRecord createRecord(){
    	 
    	 
    	 return new NdefRecord(
    			 NdefRecord.TNF_MIME_MEDIA,
    			 new byte[0],
                 new byte[0], "com.gujing.main.SosAppActivity".getBytes(Charset.forName("US-ASCII"))
    			 );
    	 
    	 
    	 /*
    	 NdefRecord uriRecord = new NdefRecord(
    			    NdefRecord.TNF_ABSOLUTE_URI ,
    			    "http://developer.android.com/index.html".getBytes(Charset.forName("US-ASCII")),
    			    new byte[0], new byte[0]);
    	 return uriRecord;
    	 */
    	 
    	 /*
    	 return new NdefRecord(
    			 NdefRecord.TNF_MIME_MEDIA,
    			 "application/com.android.TestNfc".getBytes(Charset.forName("US-ASCII")),
                 new byte[0], "com.gujing".getBytes(Charset.forName("US-ASCII"))
    			 );
    	 */
     }
    
    
    

    @Override
    public void onPause() {
        super.onPause();
        if (mAdapter != null) mAdapter.disableForegroundDispatch(this);
    }
}
